﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CartDetails : BasePage
{
    protected Asah.SiteWorx.Commerce.ShoppingCart MyShoppingCart
    {
        get
        {
            if (Session["MyCart"] == null)
                Session["MyCart"] = new Asah.SiteWorx.Commerce.ShoppingCart();
            return (Asah.SiteWorx.Commerce.ShoppingCart)Session["MyCart"];
        }
        set
        {
            Session["MyCart"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadCart();
        }
    }

    private void LoadCart()
    {
        gvShoppingCart.DataSource = MyShoppingCart.CartItems;
        gvShoppingCart.DataBind();

        btnCheckout.Enabled = MyShoppingCart.CartItems.Count > 0;
        btnUpdateCart.Enabled = MyShoppingCart.CartItems.Count > 0;
    }
   protected void btnUpdateCart_Click(object sender, EventArgs e)
    {
        UpdateCart();
    }

    private void UpdateCart()
    {
        foreach (GridViewRow row in gvShoppingCart.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                Label lblItemNumber = (Label)row.FindControl("lblItemNumber");
                TextBox txtQuantity = (TextBox)row.FindControl("txtQuantity");

                string itemNumber = lblItemNumber.Text;
                int quantity = Convert.ToInt32(txtQuantity.Text);

                MyShoppingCart.UpdateCart(itemNumber, quantity);
            }
        }
        LoadCart();
    }
    protected void btnCheckout_Click(object sender, EventArgs e)
    {
        Response.Redirect("Checkout.aspx", true);
    }
    
    protected void gvShoppingCart_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        MyShoppingCart.CartItems.RemoveAt(e.RowIndex);
        LoadCart();
    }
    protected void gvShoppingCart_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label lblGrandTotal = (Label)e.Row.FindControl("lblGrandTotal");
            lblGrandTotal.Text = String.Format("{0:c}", MyShoppingCart.GetCartTotal());
        }
    }
}
